using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.Enum.System;
using net_work.IService.BackgroundTask.IService;

namespace net_work.Controllers.Sys;

[Route("api/[controller]")]
[ApiController]
public class TcrAndStuExcelController(ITcrAndStuExcelService tcrAndStuExcelService) : ControllerBase
{
    /// <summary>
    /// 创建教师导入Excel任务
    /// </summary>
    /// <param name="file">文件</param>
    /// <returns>任务ID</returns>
    [HttpPost("teacherImport")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> CreateTeacherTask(IFormFile file)
    {
        if (file.Length <= 0 || file.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            return AjaxResult.Error("文件无效");
        }

        var taskId = await tcrAndStuExcelService.CreateTask(file, TaskType.ImportTeacherExcel);

        return AjaxResult.Success(data: taskId);
    }

    /// <summary>
    /// 获取教师导入模版
    /// </summary>
    /// <returns>Excel文件</returns>
    [HttpGet("teacherTemplate")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public IActionResult DownloadTeacherTemplate()
    {
        // 生成模板
        var fileContent = tcrAndStuExcelService.TeacherExport();

        // 返回 Excel 文件
        return File(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "教师导入模版.xlsx");
    }
    
    /// <summary>
    /// 创建学生导入Excel任务
    /// </summary>
    /// <param name="file">文件</param>
    /// <returns>任务ID</returns>
    [HttpPost("studentImport")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> CreateStudentTask(IFormFile file)
    {
        if (file.Length <= 0 || file.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            return AjaxResult.Error("文件无效");
        }

        var taskId = await tcrAndStuExcelService.CreateTask(file, TaskType.ImportStudentExcel);

        return AjaxResult.Success(data: taskId);
    }

    /// <summary>
    /// 获取学生导入模版
    /// </summary>
    /// <returns>Excel文件</returns>
    [HttpGet("studentTemplate")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public IActionResult DownloadStudentTemplate()
    {
        // 生成模板
        var fileContent = tcrAndStuExcelService.StudentExport();

        // 返回 Excel 文件
        return File(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "学生导入模版.xlsx");
    }
    
    /// <summary>
    /// 获取任务状态
    /// </summary>
    /// <param name="taskId">任务ID</param>
    /// <returns>任务状态</returns>
    [HttpPost("taskStatus")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> GetTaskStatus([FromBody]string taskId)
    {
        var taskStatus = await tcrAndStuExcelService.GetTaskStatus(taskId);

        return AjaxResult.Success(new { taskStatus });
    }
}